package com.fh.login;

import com.fh.admin.entity.UmsAdmin;
import com.fh.admin.service.IUmsAdminService;
import com.fh.login.token.ProcessTokenUtils;
import com.fh.login.token.TokenCommons;
import com.fh.result.ResponseEnum;
import com.fh.result.ResultObject;
import com.fh.security.AdminUserDetails;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private IUmsAdminService adminService;

    @Autowired
    private ProcessTokenUtils processTokenUtils;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping
    public ResultObject loginAction(@RequestParam String username, @RequestParam String password, HttpServletRequest request){
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            return ResultObject.error(ResponseEnum.IS_NULL);
        }
       /* UmsAdmin admin=adminService.getUserByUsername(username);
        if(admin == null){
            return ResultObject.error(ResponseEnum.ACCOUNT_NOT_EXIST);
        }
        if(!MD5Util.getMD5(password).equals(admin.getPassword())){
            return ResultObject.error(ResponseEnum.PASSWORD_ERROR);
        }*/


        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if(!passwordEncoder.matches(password,userDetails.getPassword())){
            throw new BadCredentialsException("用户密码不正确");
        }

        UsernamePasswordAuthenticationToken authenticationToken =new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //判断完成生成Token
        AdminUserDetails adminUserDetails=(AdminUserDetails) userDetails;
        UmsAdmin admin =adminUserDetails.getUmsAdmin();
        String token = processTokenUtils.createToken(admin);
        String typeName= TokenCommons.getDeviceType(request);

        String typeTokeKey=TokenCommons.typeTokenKey(admin.getUsername(),typeName);
        Set<String>set=redisTemplate.keys(typeTokeKey);
        if (set.size()>0){
            redisTemplate.delete(set);
        }

        redisTemplate.opsForValue().set(TokenCommons.redisTokenKey(admin.getUsername(),token,typeName),System.currentTimeMillis(
        ),TokenCommons.exp_time, TimeUnit.MINUTES);
        return ResultObject.success(token);
    }

    @GetMapping
    public void deleteToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization-token");
        ResultObject resultObject = processTokenUtils.resolverToken(token);

        if (resultObject.getCode() == 200) {
            Claims claims = (Claims) resultObject.getData();
            String username = (String) claims.get("username");
            String typeName = TokenCommons.getDeviceType(request);
            /*获取key值*/
            String redisKey = TokenCommons.redisTokenKey(username, token, typeName);

            String userKey= TokenCommons.userKey(username,"user");
            String roleKey= TokenCommons.userKey(username,"role");
            String permissionKey= TokenCommons.userKey(username,"permission");

            if (redisTemplate.hasKey(redisKey)) {
                redisTemplate.delete(redisKey);
            }
            if (redisTemplate.hasKey(userKey)) {
                redisTemplate.delete(userKey);
            }
            if (redisTemplate.hasKey(roleKey)) {
                redisTemplate.delete(roleKey);
            }
            if (redisTemplate.hasKey(permissionKey)) {
                redisTemplate.delete(permissionKey);
            }
        }
    }

}

